package com.design_patterns.singleton;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-08-23 15:47
 **/
public class SynchronizedLazyLoading {


    private static SynchronizedLazyLoading INSTANCE;

    private SynchronizedLazyLoading() {

    }

    /**
     * 在方法上加synchronized ，可以满足，但是影响效率
     *
     * @return
     */
    public static synchronized SynchronizedLazyLoading getInstance() {
        if (INSTANCE == null) {
//            模拟初始化过程浪费的时间
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            INSTANCE = new SynchronizedLazyLoading();
        }
        return INSTANCE;
    }

    /**
     * 在需要加锁的时候加锁
     *  不满足只有一个实例
     * @return
     */
    public static SynchronizedLazyLoading getInstance2() {
        if (INSTANCE == null) {
//            模拟初始化过程浪费的时间
            synchronized (SynchronizedLazyLoading.class) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                INSTANCE = new SynchronizedLazyLoading();
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                System.err.println(SynchronizedLazyLoading.getInstance().hashCode());
            }).start();
        }
    }
}
